package com.crm.service.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.crm.model.ConsultInfoManage;
import com.crm.model.SysUser;
import com.crm.util.FdfsUtil;
import com.crm.util.JsonUtil;
import com.crm.util.PropertyReaderUtil;
import com.crm.util.SessionModel;
import com.crm.util.SessionUtils;
import com.crm.util.ValidateUtil;

@Controller
@RequestMapping("/stuServiceCenter")
public class StuServiceCenterController {
	
	private static final String  fdfsPath = PropertyReaderUtil.getValue("/config.properties", "fdfs_host");
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request){
		SysUser user = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		request.setAttribute("user", user);
		return "serviceCenter/serviceCenter";
	}
	/**
	 * 待做
	 * 上传学生资料
	 * @param request
	 * @param uploadFile
	 * @param avatar_data
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadStuData")
	@ResponseBody
	public Map<String, Object> uploadStuData(HttpServletRequest request,
			@RequestParam("avatar_file") MultipartFile uploadFile, String avatar_data,String infoManageId) throws Exception{
		Map<String,Object> retMap = new HashMap<>();
		long limitSize= 2*1024*1024;
		long fileSize = uploadFile.getSize();
		if(fileSize>limitSize){
			retMap.put("msg", "文件大小超过限制");
			return retMap;
		}
		String originalFileName = uploadFile.getOriginalFilename();
		String fileExt = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
	    Map<String, Object> dataMap = JsonUtil.toMap(avatar_data);
	    BufferedImage img = ImageIO.read(uploadFile.getInputStream());
	   
	    int x = Double.valueOf(String.valueOf(dataMap.get("x"))).intValue();
	    int y = Double.valueOf(String.valueOf(dataMap.get("y"))).intValue();
	    int width = Double.valueOf(String.valueOf(dataMap.get("width"))).intValue();
	    int height = Double.valueOf(String.valueOf(dataMap.get("height"))).intValue();
	    if(x<0||y<0){
	    	retMap.put("msg", "在图像框内截取");
			return retMap;
	    }
	    img = img.getSubimage(x, y, width, height);
	    ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    ImageIO.write(img, fileExt, bos);
		
		String files[] = {};
		files = FdfsUtil.uploadFile(bos.toByteArray(), originalFileName,fileExt,fileSize);
		if(!ValidateUtil.isEmpty(files)){
			retMap.put("error", 0);
			retMap.put("url", fdfsPath + files[0] + "/" + files[1]);
			return retMap;
		}else{
			retMap.put("msg", "上传错误！");
		}
		return retMap;
	}
	
	@RequestMapping("/downloadStuData")
	public void downloadStuData(ConsultInfoManage infoManage,HttpServletRequest request,HttpServletResponse response) throws Exception{
		/*zp:照片 idcard:身份证  zs:证书 gzzm:工作证明  rzbg:认证报告*/
		//group1/M00/00/00/PM2Ielhy7NiACr1MAAAYLvHBeIw652.jpg
		infoManage = new ConsultInfoManage();
		infoManage.setInfoManageId("8f594983-bcf3-4234-8118-f198192274bf,8f594983-bcf3-4234-8118-f198192274bf");
		infoManage.setStudentName("admin,admin");
		infoManage.setStudentPhone("18210308141,18210308141");
		String[] infoManageIdArr = infoManage.getInfoManageId().split(",");
		String[] stuNameArr = infoManage.getStudentName().split(",");
		String[] phoneArr = infoManage.getStudentPhone().split(",");
		String[] dataJsonArr = new String[infoManageIdArr.length];
		dataJsonArr[0]="{\"zp\":\"group1/M00/00/00/PM2Ielhy7NiACr1MAAAYLvHBeIw652.jpg\",\"idcard\":\"group1/M00/00/00/PM2Ielhy7NiACr1MAAAYLvHBeIw652.jpg\"}";
		dataJsonArr[1]="{\"zp\":\"group1/M00/00/00/PM2Ielhy7NiACr1MAAAYLvHBeIw652.jpg\",\"idcard\":\"group1/M00/00/00/PM2Ielhy7NiACr1MAAAYLvHBeIw652.jpg\"}";
		dataJsonArr[0]=null;
		dataJsonArr[1]=null;
		String filePath = "/tempFile"+UUID.randomUUID().toString()+".zip";
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream( filePath)); 
		BufferedOutputStream bos = new BufferedOutputStream(out);
		for(int i=0;i<infoManageIdArr.length;i++){
			//姓名-手机号-uuId 
			String stuDataDirectoryName = stuNameArr[i]+"-"+phoneArr[i]+"-"+UUID.randomUUID().toString();
			if(dataJsonArr[i]==null){
				stuDataDirectoryName=stuDataDirectoryName+"-无资料";
				zip(out,bos, null,stuDataDirectoryName);
				continue;
			}
			Map<String,String> dataMap = JsonUtil.toMap(dataJsonArr[i]);
			Iterator<Entry<String,String>> iterator =dataMap.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String, String> entry = iterator.next();
				String suffix = entry.getValue().substring(entry.getValue().lastIndexOf("."),entry.getValue().toString().length());
				String dataFileName = stuDataDirectoryName+File.separator+entry.getKey()+suffix;
				URL url=null;
				HttpURLConnection conn=null;
				InputStream inStream=null;
				try {
					url = new URL(fdfsPath+entry.getValue());
					conn = (HttpURLConnection) url.openConnection();
					conn.setConnectTimeout(10 * 1000);
					inStream= new BufferedInputStream(conn.getInputStream());
				} catch (Exception e) {
					inStream=null;
					dataFileName=dataFileName.substring(0, dataFileName.lastIndexOf("."))+"-未找到图片"+dataFileName.substring(dataFileName.lastIndexOf("."), dataFileName.length());
				}
				
				zip(out,bos, inStream,dataFileName);
			}
			
		}
		closeInputStream(out,bos);
		String downloadName ="学生资料"; 
		if(stuNameArr.length==1) downloadName=stuNameArr[0]+"资料";
		downloadZip(response,filePath,downloadName);
	}
	
	
	private static void zip(ZipOutputStream zipOut,BufferedOutputStream bo, InputStream in,String base) throws Exception {  
        System.out.println("压缩中...");  
        zipOut.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base  
        System.out.println(base);
        if(in==null)return;
        BufferedInputStream bi = new BufferedInputStream(in);  
        byte[] byteArr = new byte[2048];
        int length=-1;
        while ((length = bi.read(byteArr)) != -1) {  
            bo.write(byteArr,0,length); // 将字节流写入当前zip目录  
        }
        zipOut.flush();
        bo.flush();
        bi.close();  
        in.close(); // 输入流关闭   
        System.out.println("压缩完成");  
    }
	
	private static void closeInputStream(ZipOutputStream out,BufferedOutputStream bos) throws IOException{
		if(out!=null){
			out.flush();
			out.close();
		}
		if(bos!=null){
			bos.flush();
			bos.close();
		}
		
	}
	
	private static void downloadZip(HttpServletResponse response, String filePath, String fileName) {
		OutputStream os = null;
		FileInputStream fis = null;
		File file = new File(filePath);
		try {
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + fileName + ".zip");
			fis = new FileInputStream(file);
			os = response.getOutputStream();
			byte[] b = new byte[1024];
			int num = 0;
			while ((num = fis.read(b)) > 0) {
				os.write(b, 0, num);
			}
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
					fis = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
					os = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			file.delete();
		}
	}


}
